package cn.itcast.util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author lyy
 * @Description TODO 高德地图 行驶距离测量
 * @PACKAGE_NAME: cn.itcast.util
 * @ClassName Distance
 * @Date 2020/7/24 16:28
 * @DAY_NAME_FULL: 星期五
 * @Version 1.0
 **/
@Component
public class Distance {
    /*
     * Java http 请求
     */
    public static String loadJson (String url) {
        StringBuilder json = new StringBuilder();
        try {
            //下面那条URL请求返回结果无中文，可不转换编码格式
            URL urlObject = new URL(url);
            URLConnection uc = urlObject.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json.toString();
    }
    /*
     * 高德地图WebAPI : 行驶距离测量
     */
    public static String distance(String origins,String destination) {
        int type = 1;
        String url = "http://restapi.amap.com/v3/distance?"
                + "origins="+origins
                +"&destination="+destination
                +"&type="+type
                +"&key=41c9141e5b31e5eb9d8c770835d4c59f";
        JSONObject jsonobject = JSONObject.fromObject(loadJson(url));
        System.out.println(jsonobject.toString());
        JSONArray resultsArray = jsonobject.getJSONArray("results");
        JSONObject distanceObject = resultsArray.getJSONObject(0);
        String distance = distanceObject.getString("distance");
        return distance;
    }
}
